<script setup lang="ts">
import { getCourseSubjectsList, deleteCourseSubjects } from '@/api/classroom';
import { ref, onMounted } from 'vue';
import { showToast, showDialog } from 'vant';
import { Empty as VanEmpty, Skeleton as VanSkeleton } from 'vant';
import { useRouter } from 'vue-router';
import CreateSubjectModal from './CreateSubjectModal.vue';

const props = defineProps<{ courseId: string }>();
const router = useRouter();

const assignments = ref<any[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const showCreateModal = ref(false);

const fetchAssignments = async () => {
  if (!props.courseId) return;
  
  try {
    loading.value = true;
    const res = await getCourseSubjectsList(props.courseId);
    
    if (res && res.data) {
      assignments.value = res.data.filter(item => item.type === 'HOMEWORK');
    }
  } catch (error) {
    showToast('获取作业列表失败');
    console.error('获取作业列表失败:', error);
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

const onRefresh = () => {
  refreshing.value = true;
  fetchAssignments();
};

const handleDelete = (id: string, title: string) => {
  showDialog({
    title: '删除作业',
    message: `确定要删除"${title}"作业吗？`,
    showCancelButton: true,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  }).then(async () => {
    try {
      await deleteCourseSubjects(id);
      showToast('删除成功');
      fetchAssignments();
    } catch (error) {
      showToast('删除失败');
      console.error('删除作业失败:', error);
    }
  });
};

const viewAssignment = (subjectId: string) => {
  router.push({
    name: 'SubjectHome',
    query: { 
      id: subjectId,
      courseId: props.courseId,
      type: 'HOMEWORK'
    }
  });
};

const openCreateModal = () => {
  showCreateModal.value = true;
};

const onCreated = () => {
  showCreateModal.value = false;
  fetchAssignments();
};

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const getAssignmentStatus = (startTime: string, endTime: string) => {
  const now = new Date();
  const start = new Date(startTime);
  const end = new Date(endTime);
  
  if (now < start) return { text: '未开始', color: '#909399' };
  if (now > end) return { text: '已结束', color: '#F56C6C' };
  return { text: '进行中', color: '#67C23A' };
};

onMounted(() => {
  fetchAssignments();
});
</script>

<template>
  <div class="assignment-container">
    <div class="header">
      <h3 class="title">作业管理</h3>
      <van-button type="primary" size="small" icon="plus" @click="openCreateModal">添加作业</van-button>
    </div>
    
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-empty v-if="!loading && assignments.length === 0" description="暂无作业" />
      
      <div v-else class="assignment-list">
        <van-skeleton title :row="3" :loading="loading" v-for="i in 3" :key="`skeleton-${i}`" v-if="loading" />
        
        <div v-else v-for="item in assignments" :key="item.id" class="assignment-item" @click="viewAssignment(item.subjectId)">
          <div class="assignment-info">
            <div class="assignment-title">{{ item.title || '作业' }}</div>
            <div class="assignment-time">
              <van-icon name="clock-o" /> {{ formatDate(item.startTime) }} 至 {{ formatDate(item.endTime) }}
            </div>
            <div class="assignment-status">
              <van-tag :color="getAssignmentStatus(item.startTime, item.endTime).color">
                {{ getAssignmentStatus(item.startTime, item.endTime).text }}
              </van-tag>
            </div>
          </div>
          <div class="assignment-actions">
            <van-button 
              class="delete-btn" 
              size="mini" 
              icon="delete-o" 
              type="danger" 
              plain 
              @click.stop="handleDelete(item.id, item.title || '作业')"
            />
          </div>
        </div>
      </div>
    </van-pull-refresh>
    
    <CreateSubjectModal 
      v-model:show="showCreateModal" 
      :course-id="props.courseId" 
      type="HOMEWORK" 
      title="添加作业"
      @created="onCreated" 
    />
  </div>
</template>

<style lang="scss" scoped>
.assignment-container {
  padding: 16px 0;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .title {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .assignment-list {
    .assignment-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px;
      margin-bottom: 12px;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      transition: transform 0.2s;
      
      &:active {
        transform: scale(0.99);
        background-color: #f9f9f9;
      }
      
      .assignment-info {
        flex: 1;
        
        .assignment-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 8px;
        }
        
        .assignment-time {
          display: flex;
          align-items: center;
          font-size: 13px;
          color: #666;
          margin-bottom: 8px;
          
          .van-icon {
            margin-right: 4px;
          }
        }
      }
      
      .assignment-actions {
        margin-left: 16px;
        
        .delete-btn {
          opacity: 0.8;
        }
      }
    }
  }
}
</style>